package directmemory;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author ZhengDp
 * @Date 2023/5/12 22:20
 * @Description 演示ByteBuffer 作用（直接内存）
 */
public class DirectMemory_Demo1 {

    private static String FROM = "";
    private static String TO = "";

    private static int _1Mb = 1024 * 1024;


    private static void directBuf(){
        long start = System.nanoTime();
        try(FileChannel from = new FileInputStream(FROM).getChannel();
        FileChannel to = new FileOutputStream(TO).getChannel()) {
            // 直接内存使用
            ByteBuffer bb = ByteBuffer.allocateDirect(_1Mb);
            while(true) {
                int len = from.read(bb);
                if(len == -1) {
                    break;
                }
                bb.flip();
                to.write(bb);
                bb.clear();
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        long end = System.nanoTime();
        System.out.println("directBuff 用时 ： " + (end -start) / 1000_000.0);
    }


    // 传统阻塞IO
    private static void io(){
        long start = System.nanoTime();
        try(FileInputStream from = new FileInputStream(FROM);
            FileOutputStream to = new FileOutputStream(TO)) {
            byte[] buf = new byte[_1Mb];
            while(true) {
                int len = from.read(buf);
                if(len == -1) {
                    break;
                }
                to.write(buf,0,len);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        long end = System.nanoTime();
        System.out.println("io 用时 ： " + (end - start) / 1000_000.0);
    }
}
